<template>
    <div class='system-common-container'>
        <el-card shadow='hover' :body-style="{ paddingBottom: '0' }">
            <el-form :model='state.queryParams' ref='queryForm' :inline='true'>
                <el-form-item :label-width='70' label='产品名称'>
                    <el-select :clearable='true' class='ml10' style='width: 100%'
                               v-model='state.queryParams.productId' placeholder='请选择' filterable>
                        <el-option v-for='item in state.productDict' :key='item.value' :label='item.label'
                                   :value='item.value'/>
                    </el-select>
                </el-form-item>
                <el-form-item :label-width='70' label='渠道名称'>
                    <el-select :clearable='true' class='ml10' style='width: 100%'
                               v-model='state.queryParams.channelId' placeholder='请选择'>
                        <el-option v-for='item in state.channelDict' :key='item.value' :label='item.label'
                                   :value='item.value'/>
                    </el-select>
                </el-form-item>
                <el-form-item :label-width='70' label='省份'>
                    <el-select :clearable='true' class='ml10' style='width: 100%'
                               v-model='state.queryParams.province' placeholder='请选择'>
                        <el-option v-for='item in optionDict.provinceDict' :key='item.value' :label='item.label'
                                   :value='item.value'/>
                    </el-select>
                </el-form-item>
                <el-form-item :label-width='70' label='日期'>
                    <el-date-picker class='ml10' v-model='state.queryParams.dateRange' type='daterange'
                                    inputmode="none"
                                    :shortcuts="selectShortcuts"
                                    placeholder='日期'
                                    date-format="YYYY/MM/DD" value-format="YYYY-MM-DD"
                                    :disabled-date="disableFutureDates"
                                    range-separator='至' start-placeholder='开始日期' end-placeholder='结束日期'
                                    :picker-options="{firstDayOfWeek: 1 }"
                                    :clearable="false"
                    />
                </el-form-item>
                <el-form-item>
                    <el-button-group>
                        <el-button type="primary" icon="ele-Search" @click="handleQuery"
                                   :loading='state.loading'>
                            查询
                        </el-button>
                        <el-button icon="ele-Refresh" @click="resetQuery" v-auth="'esOrder:query'"> 重置</el-button>
                    </el-button-group>
                    <el-button size="default" type="success" plain icon="ele-FolderOpened" :loading="state.loading"
                               @click.stop.prevent="exportExcel" v-auth="'esOrder:query'"> 导出
                    </el-button>
                    <el-button size="default" type="warning" plain class="ml10" @click="onOpenAddDialog()">
                        <el-icon>
                            <Upload/>
                        </el-icon>
                        上传
                    </el-button>
                </el-form-item>

            </el-form>
        </el-card>
        <!--  -->
        <el-card shadow='hover' style='margin-top: 8px'>
            <el-table :data="state.data" style="width: 100%" :border="true" stripe highlight-current-row>
                <el-table-column label="日期" prop="subscribeDate" min-width="80" header-align="center" align="center"/>
                <el-table-column label="渠道名称" prop="channelName" min-width="80" align="center" header-align="center"/>
                <el-table-column label="省份" prop="province" min-width="80" align="center" header-align="center"/>
                <el-table-column label="总数" prop="userCount" header-align="center" align="right"/>
                <el-table-column label="留存数" prop="subscribe" header-align="center" align="right"/>
                <el-table-column label="退订数" prop="unsubscribe" header-align="center" align="right"/>
                <el-table-column label="留存率" prop="subscribeRate" header-align="center" align="right">
                    <template #default="scope">
						<span :class='classObject(scope.row.subscribeRate)'> {{
                                scope.row.subscribeRate.toFixed(2)
                            }}%</span>
                    </template>
                </el-table-column>
                <el-table-column label="退订率" prop="unsubscribeRate" header-align="center" align="right">
                    <template #default="scope">
                        {{ scope.row.unsubscribeRate.toFixed(2) }}%
                    </template>
                </el-table-column>
                <el-table-column v-for="(date, index) in state.uniqueDates" :key="index" :label="date"
                                 width="80" align="right">
                    <template #default="scope">
                        {{ getUnsubscribeByDate(scope.row.detail, date) }}
                    </template>
                </el-table-column>
            </el-table>
            <div class='table-pagination'>
                <el-pagination @size-change='onHandleSizeChange' @current-change='onHandleCurrentChange'
                               :page-sizes='pageSizes' :current-page='state.queryParams!.pageNum' background
                               :page-size='state.queryParams.pageSize'
                               layout='sizes,total, ->, prev, pager, next, jumper'
                               :total='state.total' v-if='state.total !== 0'>
                </el-pagination>
            </div>
        </el-card>
        <importUnsubscribeDialog ref="importUnsubscribeDialogRef" @refresh="handleQuery()"/>
    </div>
</template>

<script setup lang='ts' name='esRetainReport'>

import {reactive, onMounted, computed, ref, defineAsyncComponent} from 'vue';
import {ElMessage} from 'element-plus';
import {selectShortcuts, disableFutureDates, todayDate} from '/@/utils/dateHelper';
import {getFileName, downloadByData} from '/@/utils/download';
import apiBusinessList from '/@/api/exocytosis/business';
import apiProductList from '/@/api/exocytosis/product';
import apiChannelList from '/@/api/exocytosis/channel';
import SysEsReportApi from '/@/api/exocytosis/report'
import {sysBaseDict} from "/@/api/models";
import {optionDict} from "/@/const/dict";

// 引入组件
const ImportUnsubscribeDialog = defineAsyncComponent(() => import('/@/views/exocytosis/order/retainReport/component/editEsImportUnsubscribe.vue'));

// 定义变量内容
const importUnsubscribeDialogRef = ref<InstanceType<typeof ImportUnsubscribeDialog>>();

const state = reactive({
    loading: false,
    data: [],
    total: 0 as any,
    uniqueDates: [],
    businessDict: [] as sysBaseDict[],
    productDict: [] as sysBaseDict[],
    channelDict: [] as sysBaseDict[],
    provinceDict: [] as sysBaseDict[],
    queryParams: {
        pageNum: 1,
        pageSize: 20,
        dateRange: [todayDate(), todayDate()],
        productName: undefined,
        channelName: undefined,
        province: undefined,
        businessId: undefined,
        productId: undefined,
        channelId: undefined,
    },
});

onMounted(async () => {
    await businessDictQuery();
    await productDictQuery()
    await channelDictQuery()
});

// 业务列表
const businessDictQuery = async () => {
    apiBusinessList().queryAll().then((res) => {
        if (res.data.resCode === '0000')
            state.businessDict = res.data.result ?? [];
    });
};

// 产品列表
const productDictQuery = async () => {
    apiProductList().queryAll().then((res) => {
        if (res.data.resCode === '0000')
            state.productDict = res.data.result ?? [];
    });
};

// 渠道列表
const channelDictQuery = async () => {
    apiChannelList().queryAll().then((res) => {
        if (res.data.resCode === '0000')
            state.channelDict = res.data.result ?? [];
    });
};

// 查询操作
const handleQuery = async () => {
    // 1. 验证日期范围
    if (state.queryParams.dateRange.length === 0) {
        return ElMessage.warning('请先选择日期');
    }

    if (!state.queryParams.productId) {
        return ElMessage.error('请选择产品信息！');
    }

    try {
        state.loading = true;

        // 2. 参数处理（自动过滤空值）
        const params = {
            ...state.queryParams,
            // operatorPlatform: state.queryParams.operatorPlatform || undefined // 自动转换空字符串
        };

        // 3. API请求
        const {data} = await SysEsReportApi().QueryPage(params);

        // 4. 响应处理（安全取值）
        state.data = data?.result?.items || [];
        state.total = data?.result?.total || 0;

        // 获取所有唯一的退订日期，并按时间顺序排序
        const datesSet = new Set();
        state.data.forEach(item => item.detail.forEach(d => datesSet.add(d.unsubscribeDate)));
        state.uniqueDates = Array.from(datesSet).sort();

    } catch (error) {
        ElMessage.error('数据加载失败');
    } finally {
        state.loading = false;
    }
};

// 重置操作
const resetQuery = () => {
    // 1. 批量重置为undefined
    const keepKeys: string[] = ['pageNum', 'pageSize', 'dateRange']; // 声明需要保留的字段
    Object.keys(state.queryParams).forEach(key => {
        if (!keepKeys.includes(key))
            state.queryParams[key] = undefined;
    });
    // 2. 单独处理日期
    state.queryParams.dateRange = [todayDate(), todayDate()];
    state.data = [];
}

// 分页改变
const onHandleSizeChange = (val: number) => {
    state.queryParams.pageSize = val;
    handleQuery();
};
// 分页改变
const onHandleCurrentChange = (val: number) => {
    state.queryParams.pageNum = val;
    handleQuery();
};

const pageSizes = computed(() => {
    let defaultSizes = [20, 50, 100, 1500];
    if (state.queryParams!.pageSize) {
        if (!defaultSizes.includes(state.queryParams!.pageSize)) {
            defaultSizes.push(state.queryParams!.pageSize);
        }
    }
    return defaultSizes;
});

const getUnsubscribeByDate = (detail, date) => {
    const detailItem = detail.find(d => d.unsubscribeDate === date);
    return detailItem ? detailItem.unsubscribe : '';
};

// 导出日志
const exportExcel = async () => {
    if (state.queryParams.productId == '') {
        return ElMessage.error('请选择产品信息！');
    }
    state.loading = true;
    SysEsReportApi().ExportExcelRetainReport(state.queryParams).then((res) => {
        // console.log("excel.." + JSON.stringify(res));
        const fileName = getFileName(res.headers);
        downloadByData(res.data as any, fileName);
        state.loading = false;
    });
};

const classObject = (retain1HourRate: number) => {
    let colorClass = '';
    if (retain1HourRate >= 60) {
        colorClass = 'text-success';
    } else if (retain1HourRate >= 40) {
        colorClass = 'text-warning';
    } else {
        colorClass = 'text-danger';
    }
    return colorClass;
};

// 新增弹窗
const onOpenAddDialog = () => {
    importUnsubscribeDialogRef.value?.openDialog();
};

</script>

<style scoped lang='scss'>
.el-data-table :deep(.el-button + .el-button) {
    margin-left: 6px;
}

.el-data-table :deep(.table-header-cell) .cell {
    color: var(--el-text-color-primary);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.table-pagination {
    box-sizing: border-box;
    width: 100%;
    max-width: 100%;
    background-color: var(--ba-bg-color-overlay);
    padding: 13px 15px;
}

.text-primary {
    color: var(--el-color-primary);
}

.text-success {
    color: var(--el-color-success);
}

.text-info {
    color: var(--el-color-info);
}

.text-warning {
    color: var(--el-color-warning);
}

.text-danger {
    color: var(--el-color-danger);
}

.table-copy {
    .el-table__expanded-cell {
        padding: 0 !important;
    }

    td {
        padding: 0 !important;
    }
}
</style>
